WithGlobalStore   A
last analyzed

Complexity

Total Complexity 1

Size/Duplication

Total Lines 22
Duplicated Lines 0 %

Importance

Changes 0
Metric Value
wmc 1
eloc 18
dl 0
loc 22
rs 10
c 0
b 0
f 0

1 Function

Rating   Name   Duplication   Size   Complexity  
A render 0 6 1
1
import React from 'react'
2
import hoistNonReactStatic from 'hoist-non-react-statics'
3
import { view, set, over, curry, mergeDeepLeft } from 'ramda'
4
5
import getDisplayName from './getDisplayName'
6
import { inGlobalStateLens } from './globalStateLens'
7
8
/**
9
 * This function will create and return a HOC for adding a provider to a component with global state.
10
 * @param {object} init The initial state
11
 * @param {React.Context} GlobalStoreProvider The GlobalStoreContext
12
 */
13
export const createWithGlobalStore = curry(
14
  (init, GlobalStoreContext) => (Component, state = {}) => {
15
    const MemoComponent = React.memo(Component)
16
    // HOC component for providing the global state to the given component.
17
    class WithGlobalStore extends React.Component {
18
      constructor (props) {
19
        super(props)
20
        const store = {
21
          state: mergeDeepLeft(state, init),
22
          view: lens => view(inGlobalStateLens(lens), this.state),
23
          set: curry((lens, x) =>
24
            this.setState(set(inGlobalStateLens(lens), x))
25
          ),
26
          over: curry((lens, f) =>
27
            this.setState(over(inGlobalStateLens(lens), f))
28
          )
29
        }
30
        this.state = { store }
31
      }
32
33
      render () {
34
        return (
35
          <GlobalStoreContext.Provider value={this.state.store}>
36
            <MemoComponent {...this.props} />
37
          </GlobalStoreContext.Provider>
38
        )
39
      }
40
    }
41
    // Add a readable name.
42
    WithGlobalStore.displayName = `WithGlobalStore(${getDisplayName(
43
      Component
44
    )})`
45
    // Add all the non static functions to the HOC.
46
    hoistNonReactStatic(WithGlobalStore, Component)
47
    return WithGlobalStore
48
  }
49
)
50